<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="活动详情" />
      <!-- 顶部轮播图（仿照 leagueMatchesHome） -->
      <view class="banner-wrap" v-if="swiperList && swiperList.length">
        <swiper class="banner" :indicator-dots="true" :autoplay="true" :interval="3000" :circular="true">
          <swiper-item v-for="(img, index) in swiperList" :key="index">
            <view class="banner-content" @click="previewImage(img, swiperList)">
              <image :src="img" class="image_10" style="width: 100%; height: 100%" />
            </view>
          </swiper-item>
        </swiper>
      </view>
      <!-- 标题和时间 -->
      <view class="title-section">
        <view class="title">{{ eventActivityDetail.name }}</view>
        <view class="display-flex">
          <view class="mr-auto">
            <view class="time-row">
              <view class="time-label">活动时间：</view>
              <view class="time-value">
                <text>{{ formatDateOnly(eventActivityDetail.competition_time) }}</text>
                <text v-if="eventActivityDetail.end_time"> ~ </text>
                <text>{{ formatDateOnly(eventActivityDetail.end_time) }}</text>
              </view>
            </view>
            <view class="time-row">
              <view class="time-label">截止时间：</view>
              <view class="time-value">{{ formatTime(eventActivityDetail.deadline) }}</view>
            </view>
          </view>
          <view class="action-row">
            <!-- 小程序客服按钮 -->
            <button class="action-btn mr-10" open-type="contact" :session-from="sessionFrom" bindcontact="onServiceContact">
              <image :src="imgUrl + 'customerService@2x.png'" class="action-icon" />
              <text class="action-text">客服</text>
            </button>
            <view class="action-btn mr-10" @click="onShare">
              <image :src="imgUrl + 'share2@2x.png'" class="action-icon" />
              <text class="action-text">分享</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 套餐类型 -->
      <view class="section-title">套餐类型</view>
      <view class="package-card">
        <view class="package-title">培训报名费</view>
        <view class="package-row">
          <view class="package-price">
            <text>¥</text>
            <text>{{ eventActivityDetail.price ? eventActivityDetail.price : '0.00' }}</text>
          </view>
          <view class="package-btns">
            <button class="desc-btn" @click="onDesc">套餐说明</button>
            <button class="order-btn" @click="onOrder(eventActivityDetail.id)">订购</button>
          </view>
        </view>
      </view>

      <!-- 详情介绍 -->
      <view class="section-title">详情介绍</view>
      <view class="desc-card">
        <!-- 显示desc_image图片 -->
        <view v-if="eventActivityDetail.desc_image" class="desc-images">
          <image v-for="(img, index) in descImages" :key="index" :src="img" class="desc-img" mode="aspectFill"
            @click="previewImage(img, descImages)" />
        </view>
        <!-- 显示describe文本 -->
        <view v-if="eventActivityDetail.content" class="desc-text">
          <view v-if="contentLoading" class="content-loading">
            <text>内容加载中...</text>
          </view>
          <rich-text v-else :nodes="processedContent" @load="onImageLoad" @error="onImageError"></rich-text>
        </view>
      </view>
    </view>
    <!-- <movable-area class="movable-area">
      <movable-view class="fab-container" direction="all" :x="x" :y="y">
        <image :src="imgUrl + 'customerService2.png'" class="fab-icon" />
      </movable-view>
    </movable-area> -->

    <!-- 套餐说明弹窗 -->
    <uni-popup ref="descPopup" type="bottom" :mask-click="true" @open="onPopupOpen" @close="onPopupClose">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">套餐说明</text>
          <view class="popup-close" @click="closeDescPopup">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="popup-body">
          <!-- 套餐说明图片 -->
          <!-- <view v-if="eventActivityDetail.desc_image" class="popup-images">
            <image 
              v-for="(img, index) in descImages" 
              :key="index"
              :src="img" 
              class="popup-img"
              mode="aspectFill"
              @click="previewImage(img, descImages)"
            />
          </view> -->

          <!-- 套餐说明文本 -->
          <view v-if="eventActivityDetail.describe" class="popup-text">
            <text>{{ eventActivityDetail.describe }}</text>
          </view>
        </view>
      </view>
    </uni-popup>
  </scroll-view>
  <PosterCanvas ref="__poster__" :visible="posterVisible" :data="posterData" @done="(p)=>{ posterDone && posterDone(p) }"
    @close="()=> posterVisible=false" />
</template>

<script setup>
  import { ref, computed, defineExpose, watch } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { onShow } from '@dcloudio/uni-app';
  import { formatTime, formatDateOnly } from '@/utils/dateUtils.js'
  import { useRequest } from '@/api';
  import RichTextView from '@/components/RichTextView/index.vue'
  import { ShareUtils, ShareConfigGenerator } from '@/utils/shareUtils.js'
  import PosterCanvas from '@/components/PosterCanvas/PosterCanvas.vue'
  const { API_ACT_DETAIL_POST, API_NEWS_CUSTOMER_GET, API_LOGIN_WX_POST, API_ACT_PAY_POST } = useRequest()
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)
  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }
  const eventActivityDetail = ref({})
  const mainId = ref('')
  const eventActivityId = ref('')
  const contentLoading = ref(false)
  const swiperList = ref([])
  // 处理desc_image，将字符串转换为数组
  const descImages = computed(() => {
    if (!eventActivityDetail.value.desc_image) return []
    return eventActivityDetail.value.desc_image.split(',').filter(img => img.trim())
  })

  // 处理HTML内容，优化图片显示
  const processedContent = computed(() => {
    if (!eventActivityDetail.value?.content) return '';

    let content = eventActivityDetail.value.content;

    // 处理图片宽度，确保响应式
    content = content.replace(
      /style="width:\s*\d+\.?\d*px"/g,
      'style="max-width: 100%; height: auto; border-radius: 8rpx; box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);"'
    );

    // 处理没有样式的图片，添加响应式样式和点击事件
    content = content.replace(
      /<img([^>]*?)src="([^"]*?)"([^>]*)>/g,
      '<img$1src="$2"$3 style="max-width: 100%; height: auto; border-radius: 8rpx; box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1); cursor: pointer;" data-src="$2" @click="onImageTap">'
    );

    return content;
  })

  // 分享数据
  const shareData = computed(() => {
    return ShareUtils.createShareData(eventActivityDetail.value)
  })

  // 仅用于当前海报生成的临时 https 处理
  const ensureHttps = (url) => {
    if (!url) return url
    return url.startsWith('http://') ? url.replace('http://', 'https://') : url
  }

  // 弹窗ref
  const descPopup = ref(null)
  onShow(() => {
    mainId.value = '';
    getParams();
  })
  const getParams = () => {
    const pages = getCurrentPages(); // 获取当前页面栈
    const currentPage = pages[pages.length - 1]; // 获取当前页面
    console.log('currentPage', currentPage);
    const options = currentPage.options; // 获取当前页面的参数
    const { id } = options;
    console.log('id', id);
    mainId.value = id;
    getEventActivityDetail(id);

  }
  // 图片加载成功处理
  const onImageLoad = (e) => {
    console.log('图片加载成功:', e);
  }

  // 图片加载失败处理
  const onImageError = (e) => {
    console.log('图片加载失败:', e);
    // 可以在这里设置默认图片或显示错误提示
  }

  // 图片点击预览
  const onImageTap = (e) => {
    const { src } = e.target.dataset;
    if (src) {
      // 从内容中提取所有图片URL
      const imgRegex = /<img[^>]+src="([^"]+)"/g;
      const images = [];
      let match;
      while ((match = imgRegex.exec(eventActivityDetail.value.content)) !== null) {
        images.push(match[1]);
      }

      if (images.length > 0) {
        uni.previewImage({
          current: src,
          urls: images
        });
      }
    }
  }

  const getEventActivityDetail = async (id) => {
    let params = {
      id: id,
      page: 1,
      page_size: 10
    }
    eventActivityDetail.value = {}
    eventActivityId.value = ''
    contentLoading.value = true
    swiperList.value = []
    try {

      const res = await API_ACT_DETAIL_POST(params)
      console.log('getEventActivityDetail', res)

      if (res.code === 1) {
        eventActivityDetail.value = res.data;
        eventActivityId.value = res.data.id;
        swiperList.value = res.data.desc_image ? res.data.desc_image.split(',') : [];
        // // 开发环境下设置测试数据
        // if (process.env.NODE_ENV === 'development') {
        //   eventActivityDetail.value.desc_image = "http://cyty.dancelog.cn/uploads/20250802/384bc585b8119eeee109b36cb5ff7e72.png,http://cyty.dancelog.cn/uploads/20250802/384bc585b8119eeee109b36cb5ff7e72.png,http://cyty.dancelog.cn/uploads/20250802/b630fc7fb823dcef291113e796ebc366.png"
        //   eventActivityDetail.value.describe = 'jsijdhsndsahdu决赛季几点撒交货地对啊刷刷沙嗲是滴'
        // }

        // 调试输出
        console.log('eventActivityDetail:', eventActivityDetail.value)
        console.log('describe:', eventActivityDetail.value.describe)

      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    } finally {
      contentLoading.value = false
    }
  }
  // 客服会话来源参数
  const sessionFrom = ref(`活动详情-${eventActivityDetail.value.name || ''}`)
  
  // 监听活动详情变化，更新sessionFrom
  watch(() => eventActivityDetail.value.name, (newName) => {
    if (newName) {
      sessionFrom.value = `活动详情-${newName}`
    }
  })

  //联系客服 - 小程序客服
  const onServiceContact = (e) => {
    console.log('打开客服会话', e)
    console.log('会话来源:', sessionFrom.value)
    
    // 可以在这里获取客服会话信息
    // e.detail 包含客服会话相关信息
    // 例如：用户信息、会话来源等
  };
  //分享
  const onShare = () => {
    // 使用分享工具类显示分享选项
    ShareUtils.showShareOptions(['分享给好友', '分享到朋友圈', '生成分享海报', '复制链接'], (index) => {
      handleShareOption(index)
    })
  }

  // 处理分享选项
  const handleShareOption = (index) => {
    switch (index) {
      case 0:
        // 分享给好友
        ShareUtils.shareToFriend(shareData.value)
        break
      case 1:
        // 分享到朋友圈
        ShareUtils.shareToTimeline(shareData.value)
        break
      case 2:
        // 生成分享海报（富信息）
        const posterData = {
          title: eventActivityDetail.value.name || '活动详情',
          imageUrl: (descImages.value && descImages.value.length) ? descImages.value[0] : (eventActivityDetail.value.master_image || (swiperList.value && swiperList.value.length ? swiperList.value[0] : '')),
          time: `${formatDateOnly(eventActivityDetail.value.competition_time)}${eventActivityDetail.value.end_time ? ' ~ ' + formatDateOnly(eventActivityDetail.value.end_time) : ''}`,
          deadline: formatTime(eventActivityDetail.value.deadline) || '暂无截止时间',
          address: eventActivityDetail.value.address || '暂无地址信息',
          price: eventActivityDetail.value.price || '0.00'
        }
        
        // 保持原始URL，不强制转换HTTPS
        // 如果图片加载失败，会使用占位图
        console.log('准备生成海报，数据:', posterData)
        console.log('图片URL:', posterData.imageUrl)
        console.log('标题:', posterData.title)
        console.log('时间:', posterData.time)
        
        // 将富信息透传给分享工具，内部会回调到 openPoster
        ShareUtils.generatePoster({ ...shareData.value, ...posterData }, (data) => {
          console.log('海报生成完成:', data)
        })
        break
      case 3:
        // 复制链接
        const url = ShareUtils.getCurrentPageUrl()
        ShareUtils.copyLink(url, (url) => {
          console.log('链接已复制:', url)
        }, () => {
          console.log('复制失败')
        })
        break
    }
  }



  // 富文本链接点击处理
  const onLinkClick = (href) => {
    console.log('链接点击:', href)
    // 可以在这里处理链接跳转
    if (href.startsWith('http://') || href.startsWith('https://')) {
      // 打开外部链接
      uni.navigateTo({
        url: `/pages/webview/index?url=${encodeURIComponent(href)}`
      })
    }
  }

  // 图片预览
  const previewImage = (current, urls) => {
    uni.previewImage({
      urls: urls, // 当前显示图片的http链接列表
      current: current, // 当前显示图片的http链接
      indicator: 'number', // 指示器样式，支持 'number' 或 'text'
      loop: true, // 是否循环预览
      showCounter: true, // 是否显示计数器
      showStatusBar: true, // 是否显示状态栏
      longPressActions: {
        itemList: ['保存图片', '收藏'],
        success: function (data) {
          console.log('选中了第' + (data.tapIndex + 1) + '个');
        },
        fail: function (err) {
          console.log(err.message);
        }
      }
    });
  };

  // 弹窗打开事件
  const onPopupOpen = () => {
    console.log('套餐说明弹窗打开');
    console.log('当前describe内容:', eventActivityDetail.value.describe);
    console.log('当前desc_image内容:', eventActivityDetail.value.desc_image);
  };

  // 弹窗关闭事件
  const onPopupClose = () => {
    console.log('套餐说明弹窗关闭');
  };

  // 打开套餐说明弹窗
  const openDescPopup = () => {
    descPopup.value.open();
  };

  // 关闭套餐说明弹窗
  const closeDescPopup = () => {
    descPopup.value.close();
  };

  // 打开海报弹层，供 ShareUtils 调用
  const posterVisible = ref(false)
  const posterData = ref({})
  const posterDone = ref(null)
  const openPoster = (data, done) => {
    console.log('openPoster 被调用，接收到的数据:', data)
    posterData.value = data || {}
    posterVisible.value = true
    posterDone.value = typeof done === 'function' ? done : null
    
    // 调试：确认数据已设置
    console.log('posterData 已设置:', posterData.value)
    console.log('posterVisible 已设置:', posterVisible.value)
  }
  defineExpose({ openPoster })

  // const contactService = () => {
  //   uni.showToast({
  //     title: '联系客服',
  //     icon: 'none'
  //   });
  // };



  const onDesc = () => {
    // 打开套餐说明弹窗
    openDescPopup();
  };

  // 微信小程序分享配置
  // 分享给好友
  const onShareAppMessage = () => {
    return ShareConfigGenerator.generateAppMessageConfig(shareData.value)
  }

  // 分享到朋友圈
  const onShareTimeline = () => {
    return ShareConfigGenerator.generateTimelineConfig(shareData.value)
  }
  //订购
  const onOrder = () => {
    const token = uni.getStorageSync('token');
    if (!token) {
      getCodeByWx();//获取code
    } else {
      uni.navigateTo({
        url: '/pages/signUp/index?id=' + eventActivityId.value
      })
    }

  }
  const getCodeByWx = async () => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        const code = res.code;
        if (code) {
          doLogin(code)
        }
      }
    })
  }
  // 执行登录
  const doLogin = async (code) => {
    let params = {
      code
    }
    try {
      // 调用登录接口
      const res = await API_LOGIN_WX_POST(params)

      console.log('登录接口返回:', res)

      if (res.code === 1) {
        // 登录成功
        uni.setStorageSync('token', res.data.token);
        uni.setStorageSync('userInfo', res.data.userinfo);
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/signUp/index?id=' + eventActivityId.value
          })
        }, 1000)
      } else {
        throw new Error(res.msg || '登录失败');
      }
    } catch (error) {
      console.error('登录失败:', error);
      uni.showToast({
        title: error.message || '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      uni.hideLoading();
    }
  }


</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>